package com.wyait.manage.service.biz;

import java.util.Date;
import java.util.List;

import com.wyait.manage.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wyait.manage.dao.biz.ShopInfoMapper;
import com.wyait.manage.dao.biz.ShopMapper;
import com.wyait.manage.entity.biz.ShopDTO;
import com.wyait.manage.entity.biz.ShopSearchDTO;
import com.wyait.manage.entity.biz.ShopVO;
import com.wyait.manage.pojo.biz.Shop;
import com.wyait.manage.utils.PageDataResult;

@Service
public class ShopServiceImpl implements ShopService {
	private static final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);
	@Autowired
	private ShopMapper shopMapper;
	@Autowired
	private ShopInfoMapper shopInfoMapper;

	@Override
	public PageDataResult getShops(ShopSearchDTO shopSearch, int page, int limit) {
		// 时间处理
		if (null != shopSearch) {
			if (StringUtils.isNotEmpty(shopSearch.getQinsertTimeStart())
					&& StringUtils.isEmpty(shopSearch.getQinsertTimeEnd())) {
				shopSearch.setQinsertTimeEnd(DateUtil.format(new Date()));
			} else if (StringUtils.isEmpty(shopSearch.getQinsertTimeStart())
					&& StringUtils.isNotEmpty(shopSearch.getQinsertTimeEnd())) {
				shopSearch.setQinsertTimeStart(DateUtil.format(new Date()));
			}
			if (StringUtils.isNotEmpty(shopSearch.getQinsertTimeStart())
					&& StringUtils.isNotEmpty(shopSearch.getQinsertTimeEnd())) {
				if (shopSearch.getQinsertTimeEnd().compareTo(shopSearch.getQinsertTimeStart()) < 0) {
					String temp = shopSearch.getQinsertTimeStart();
					shopSearch.setQinsertTimeStart(shopSearch.getQinsertTimeEnd());
					shopSearch.setQinsertTimeEnd(temp);
				}
			}
		}
		PageDataResult pdr = new PageDataResult();
		PageHelper.startPage(page, limit);
		List<ShopDTO> urList = shopInfoMapper.getShop(shopSearch);
		// 获取分页查询后的数据
		PageInfo<ShopDTO> pageInfo = new PageInfo<>(urList);
		// 设置获取到的总记录数total：
		pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
		pdr.setList(urList);
		return pdr;
	}

	@Override
	public String setShop(Shop shop) {
		Shop shopDb = shopMapper.selectByPrimaryKey(shop.getId());
		if (shopDb == null) {
			shop.setInsertTime(new Date());
			shopMapper.insertSelective(shop);
		} else {
			shop.setUpdateTime(new Date());
			shopMapper.updateByPrimaryKeySelective(shop);
		}
		return "ok";
	}

	@Override
	public String setDelShop(Integer id, Integer isDel) {
		shopInfoMapper.setDelShop(id, isDel);
		return "ok";
	}

	@Override
	public ShopVO getShop(Integer id) {
		Shop shop = shopMapper.selectByPrimaryKey(id);
		if (shop != null) {
			ShopVO vo = new ShopVO();
			BeanUtils.copyProperties(shop, vo);
			return vo;
		}
		return null;
	}

}
